import {
  Html, Icon, noop, render,
} from 'amis';
import {
  EditorManager, EditorStoreType, isHasPluginIcon, SubRendererInfo,
} from 'amis-editor';
// import { observer } from 'mobx-react';
import { Tooltip, udp, UdpIcon } from '@cscec/udp-ui';
import React, { CSSProperties, ReactNode } from 'react';
import { Empty } from 'antd';

type PanelProps = {
  store: EditorStoreType;
  manager: EditorManager;
  groupedRenderers: Record<string, { style?: CSSProperties, items: Array<SubRendererInfo>, total: number, title?: ReactNode }>;
  className?: string;
};

type PanelStates = {
  toggleCollapseFolderStatus: boolean;
};

export class Panel extends React.Component<
PanelProps,
PanelStates
> {
  state = {
    toggleCollapseFolderStatus: false, // 用于触发重新渲染组件面板的
  };

  // 用于记录组件分类面板的折叠状态
  curCollapseFolded: {
    [propName: string]: boolean;
  } = {};

  handleRegionFilterClick = (e: React.MouseEvent) => {
    let region = e.currentTarget.getAttribute('data-value')!;

    const { store, manager } = this.props;
    region = region === store.subRendererRegion ? '' : region;
    manager.switchToRegion(region);
  };

  handleDragStart = (e: React.DragEvent, label: string) => {
    const current = e.currentTarget;
    const id = current.getAttribute('data-id')!;
    e.dataTransfer.setData(`dnd-dom/[data-id="${id}"]`, '');
  };

  handleClick = (e: React.MouseEvent) => {
    const id = e.currentTarget.getAttribute('data-dnd-id')!;
    this.props.manager.addElem(id);
  };

  // 改变折叠状态
  changeCollapseFoldStatus = (tagKey: string, event: any) => {
    this.curCollapseFolded[tagKey] = !this.curCollapseFolded[tagKey];
    this.setState({
      toggleCollapseFolderStatus: !this.state.toggleCollapseFolderStatus,
    });
    event.preventDefault();
    event.stopPropagation();
  };

  renderThumb(schema: any) {
    const { manager } = this.props;
    return schema ? (
      render(
        schema,
        {
          onAction: noop,
        },
        manager.env,
      )
    ) : (
      <p>没有预览图</p>
    );
  }

  render() {
    const { store, className } = this.props;
    const grouped = this.props.groupedRenderers || {};
    const keys = Object.keys(grouped);

    const renderIcon = (item: any) => {
      const usePluginIcon = isHasPluginIcon(item);
      const { icon } = item;
      if (usePluginIcon) {
        return <Icon icon={item.pluginIcon} />;
      } if (udp.isString(item.icon)) {
        const iconType = (UdpIcon as any)[item.icon];
        if (iconType) {
          return React.createElement(iconType);
        }
        return (
          <i
            className={udp.classNames(
              'fa-fw',
              item.icon || 'fa fa-circle-thin',
            )}
          />
        );
      } if (item.icon) {
        return item.icon;
      }
    };

    const name = udp.external.getQianKun?.().name;

    return (
      <div className={udp.classNames('ae-RendererList', className)}>
        <div className="ae-RendererList-groupWrap hoverShowScrollBar">
          {keys.length ? (
            keys.map((tag, index) => {
              const {
                style, items, total, title,
              } = grouped[tag];

              if (!total) {
                return null;
              }

              return (
                <React.Fragment key={tag}>
                  <div
                    key={`${tag}-head`}
                    className="ae-RendererList-head collapse-header"
                    onClick={(event: any) => {
                      this.changeCollapseFoldStatus(tag, event);
                    }}
                  >
                    <Tooltip overflow title={title || `${tag}(${total})`} color="#000" placement='right'>
                      <div className="nowrap" style={{ flex: 1, width: 0, paddingRight: 10 }}>{title || `${tag}(${total})`}</div>
                    </Tooltip>
                    <div
                      className={udp.classNames('expander-icon', {
                        'is-folded': !!this.curCollapseFolded[tag],
                      })}
                      title={
                                                this.curCollapseFolded[tag] ? '点击展开' : '点击折叠'
                                            }
                    >
                      <Icon icon="right-arrow-bold" />
                    </div>
                  </div>
                  <div
                    key={`${tag}-content`}
                    className={udp.classNames('ae-RendererList-group collapse-content', {
                      'is-folded': !!this.curCollapseFolded[tag],
                    })}
                  >
                    {items.map((item: any) => {
                      const key = `${index}_${item.id}`;
                      return (
                        <div
                              key={key}
                              className="ae-RendererList-item"
                              style={style}
                              draggable
                              data-id={key}
                              data-dnd-type="subrenderer"
                              data-dnd-id={item.id}
                              data-dnd-data={JSON.stringify(
                                  item.scaffold || { type: item.type },
                                )}
                              onDragStart={(e: React.DragEvent) => this.handleDragStart(e, item.name)}
                            >
                              <div
                                  className="icon-box"
                                  data-dnd-id={item.id}
                                  title={`点击添加「${item.name}」`}
                                  onClick={this.handleClick}
                                >
                                  {renderIcon(item)}
                                </div>
                              <div
                                  className="ae-RendererInfo"
                                  data-dnd-id={item.id}
                                  style={{ maxWidth: 'unset' }}
                                  onClick={this.handleClick}
                                >
                                  {item.name}
                                </div>
                              <Tooltip
                                  placement="right"
                                  getPopupContainer={() => document.body.querySelector(`div[data-qiankun="${name}"]`) || document.body}
                                  title={() => (
                                      <div>
                                          <div style={{ fontWeight: 500, fontSize: 14 }}>
                                                {item.name}
                                              </div>
                                          {item.description || item.docLink ? (
                                                <div style={{ fontWeight: 400, fontSize: 12 }}>
                                                    <Html
                                                        html={
                                                                                item.description
                                                                                  ? item.description
                                                                                  : ''
                                                                            }
                                                      />
                                                    {item.docLink && (
                                                        <a
                                                          target="_blank"
                                                          href={
                                                                                    store.amisDocHost + item.docLink
                                                                                }
                                                          rel="noreferrer"
                                                        >
                                                              详情
                                                        </a>
                                                      )}
                                                  </div>
                                              ) : null}
                                          <div style={{ minWidth: 200, maxWidth: 400 }}>
                                                {this.renderThumb(item.previewSchema)}
                                              </div>
                                        </div>
                                    )}
                                >
                                  <div className="ae-RendererIcon">
                                      <Icon icon="editor-help" className="icon" />
                                    </div>
                                </Tooltip>
                            </div>
                      );
                    })}
                  </div>
                </React.Fragment>
              );
            })
          ) : (
            <Empty description="暂时没有可用组件" style={{ marginTop: 50 }} />
          )}
        </div>
      </div>
    );
  }
}

export const RenderersPanel = Panel;
